package com.thoughtworks.impersonator.http.replay;

import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipelineCoverage;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.jboss.netty.handler.codec.http.HttpRequest;
import org.jboss.netty.handler.codec.http.HttpResponse;

import com.thoughtworks.impersonator.http.message.storage.HttpExchangeStorage;

@ChannelPipelineCoverage("one")
public class ImpersonatorHandler extends SimpleChannelUpstreamHandler {

    private final HttpExchangeStorage storage;

    public ImpersonatorHandler(HttpExchangeStorage storage) {
        this.storage = storage;
    }

    @Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
        HttpRequest request = (HttpRequest) e.getMessage();
        HttpResponse response = storage.loadResponseFor(request);
        Channel ch = e.getChannel();
        ch.write(response).addListener(ChannelFutureListener.CLOSE);
    }
}
